from process_img import *
from save2excel import *
from excel_diff import *
import os
import pandas as pd
from openpyxl import load_workbook

def adjust_column_widths(excel_path):
    wb = load_workbook(excel_path)
    for sheet_name in wb.sheetnames:
        sheet = wb[sheet_name]
        for col in sheet.columns:
            max_length = 0
            column = col[0].column_letter  # 获取列字母

            for cell in col:
                try:  # 需要尝试处理可能发生的错误
                    if len(str(cell.value)) > max_length:
                        max_length = len(cell.value)
                except:
                    pass

            adjusted_width = (max_length + 2) * 1.2  # 调整宽度
            sheet.column_dimensions[column].width = adjusted_width

    wb.save(excel_path)
def create_folder_if_not_exists(folder_path):
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

def step0_process_img(data_path, output_root_path):
    # global threshold 
    # threshold = 90

    threshold_r = 150
    threshold_g = 100
    threshold_b = 100
    threshold_rgb = [threshold_r, threshold_g, threshold_b]


    total = {'left': 35 , 'top': 945 , 'right': 390, 'bottom': 1030}
    min   = {'left': 240, 'top': 945 , 'right': 360, 'bottom': 970 }
    avg   = {'left': 240, 'top': 975 , 'right': 360, 'bottom': 1000}
    max   = {'left': 240, 'top': 1003, 'right': 360, 'bottom': 1028}
    time  = {'left': 800, 'top': 180, 'right': 1200, 'bottom': 200}

    no_color_dict = {
        "min"  : [min  , output_root_path + r"min/"],
        "avg"  : [avg  , output_root_path + r"avg/"],
        "max"  : [max  , output_root_path + r"max/"],
    }

    color_dict = {
        "time" : [time , output_root_path + r"time/"],
    }

    for key, value in no_color_dict.items():
        crop_pos = value[0]
        output_path = value[1]
        process_images(data_path, output_path, process_images_in_folder_crop, crop_pos, process_images_in_folder_preprocess, 255)

    for key, value in color_dict.items():
        crop_pos = value[0]
        output_path = value[1]
        process_images(data_path, output_path, process_images_in_folder_crop, crop_pos, process_images_in_folder_preprocess_with_color, threshold_rgb)

def set_excel_data(input_folder):
    min_folder_path = input_folder + r'min/3_text'
    avg_folder_path = input_folder + r'avg/3_text'
    max_folder_path = input_folder + r'max/3_text'
    tim_folder_path = input_folder + r'time/3_text'

    min_files = get_txt_files(min_folder_path)
    avg_files = get_txt_files(avg_folder_path)
    max_files = get_txt_files(max_folder_path)
    tim_files = get_txt_files(tim_folder_path)


    data = {'File Name': [], 'Min': [], 'Avg': [], 'Max': [], 'Tim': []}

    for file_name in avg_files.keys():
        data['File Name'].append(file_name)
        data['Min'].append(min_files.get(file_name, ''))
        data['Avg'].append(avg_files.get(file_name, ''))
        data['Max'].append(max_files.get(file_name, ''))
        data['Tim'].append(tim_files.get(file_name, ''))



    for key, values in data.items():
        if key != 'File Name':
            if key == 'Tim':
                data[key] = [process_single_string(value) for value in values]
            else:
                data[key] = [extract_numbers_from_text(value) for value in values]
    return data


def step1_save2excel(input_folder, standard_file, sheet_name, output_file):
    data = set_excel_data(input_folder)
    # 将数据写入目标文件
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    copy_file(standard_file, output_file)
    write_to_excel_in_specific_way(data, output_file, sheet_name)
    print("step1_save2excel: ", output_file)


def step2_excel_diff(standard_file, compare_file, output_file, sheet_name):
    # 示例用法
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    copy_file(standard_file, output_file)
    compare_excel(read_excel(standard_file, sheet_name), read_excel(compare_file, sheet_name), output_file, sheet_name, threshold=10)
    # adjust_column_width(output_file)
    print("step2_excel_diff: ", output_file)


def nf732_ssv6p_p():
    data_path = "./data/SSV6P-P/"
    output_root_path = "./output_SSV6P-P"

    die = "5#"
    block = "BLK1000-1001"

    standard_file = r'./output/SS V6P-P电流测试.xlsx'
    sheet_name = "SS 3DV6P"

    step0_input_path  = f"{data_path}"
    step0_output_path = f"{output_root_path}/{die}/{block}/"
    step0_process_img(data_path=step0_input_path, output_root_path=step0_output_path)


    step1_input_path = step0_output_path
    step1_output_file = f"{output_root_path}/result/result_{die}_{block}.xlsx"
    step1_save2excel(input_folder=step1_input_path, standard_file=standard_file, sheet_name=sheet_name, output_file=step1_output_file)


    compare_file = step1_output_file
    output_file = f"{output_root_path}/diff/diff_{die}_{block}.xlsx"
    step2_excel_diff(standard_file, compare_file, output_file, sheet_name)

def nf742_Bics5():
    data_path = "./data/NF742_Bics5"
    output_root_path = "./output_bics5"

    die_and_block = ["2# BLK1000-1001", "3# BLK0-1", "3# BLK1000-1001"]

    # standard_file = f"{data_path}/bics5电流测试.xlsx"
    sheet_name = "BICS5"

    for db in die_and_block:
        standard_file = f"{data_path}/bics5电流测试 {db}.xlsx"

        step0_input_path  = f"{data_path}/{db}/"
        step0_output_path = f"{output_root_path}/{db}/"
        # step0_process_img(data_path=step0_input_path, output_root_path=step0_output_path)


        step1_input_path = step0_output_path
        step1_output_file = f"{output_root_path}/result/result_{db}.xlsx"
        step1_save2excel(input_folder=step1_input_path, standard_file=standard_file, sheet_name=sheet_name, output_file=step1_output_file)


        compare_file = step1_output_file
        output_file = f"{output_root_path}/diff/diff_{db}.xlsx"
        step2_excel_diff(standard_file, compare_file, output_file, sheet_name)

def nf746_dm2320_hynixv7():
    data_path = "./data/NF746"
    output_root_path = "./output_nf746"

    block = "B24"
    pages = ["PAGE680", "PAGE688", "PAGE690", "PAGE696"]
    step0_path = {
        "PAGE680" : [f"{data_path}/{block} {pages[0]}/", f"{output_root_path}/{block} {pages[0]}/"],
        "PAGE688" : [f"{data_path}/{block} {pages[1]}/", f"{output_root_path}/{block} {pages[1]}/"],
        "PAGE690" : [f"{data_path}/{block} {pages[2]}/", f"{output_root_path}/{block} {pages[2]}/"],
        "PAGE696" : [f"{data_path}/{block} {pages[3]}/", f"{output_root_path}/{block} {pages[3]}/"],
    }

    # for __, path in step0_path.items():
    #     step0_process_img(path[0], path[1])

    all_data = []
    for __, path in step0_path.items():
        data = set_excel_data(path[1])
        all_data.append(data)
    # print(all_data)

    df = pd.DataFrame(columns=['Page Label', 'File Name', 'Min', 'Avg', 'Max', 'Tim'])
    # Populate the DataFrame
    rows = []
    for i, page_data in enumerate(all_data):
        page_label = f"{block} {pages[i]}"
        for j in range(len(page_data['File Name'])):
            row = {
                'Page Label': page_label,
                'File Name': page_data['File Name'][j],
                'Min': page_data['Min'][j],
                'Avg': page_data['Avg'][j],
                'Max': page_data['Max'][j],
                'Tim': page_data['Tim'][j]
            }
            rows.append(row)
    # print(rows)
    # df = pd.concat([df, pd.DataFrame(rows)], ignore_index=True)
    new_df = pd.DataFrame(rows).dropna(axis=1, how='all')
    df = pd.concat([df, new_df], ignore_index=True)

    # Saving to an Excel file
    output_file_path = f'{output_root_path}/output.xlsx'
    df.to_excel(output_file_path, index=False)
    adjust_column_widths(output_file_path)

if __name__ == "__main__":
    nf746_dm2320_hynixv7()
    # nf742_Bics5()